package response

import (
	"net/http"

	"gitee.com/amwfhv/tge/errors"
	"gitee.com/amwfhv/tge/log"
	"github.com/gin-gonic/gin"
)

type ErrResponse struct {
	Ret       int    `json:"ret"`
	Msg       string `json:"msg"`
	Req       string `json:"req,omitempty"`
	Reference string `json:"reference,omitempty"`
}

func WriteResponse(c *gin.Context, err error, data interface{}) {
	WriteResponseWithReq(c, err, "", data)
}

func WriteResponseWithReq(c *gin.Context, err error, req string, data interface{}) {
	if err != nil {
		log.Debugf("%+v", err)
		coder := errors.ParseCoder(err)
		c.JSON(coder.HTTPStatus(), ErrResponse{
			Ret:       coder.Code(),
			Msg:       coder.String(),
			Req:       req,
			Reference: coder.Reference(),
		})
		return
	}
	c.JSON(http.StatusOK, data)
}
